﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.IO;
using Kindohm.KSynth.Library;
using System.Windows.Threading;

namespace Kindohm.KSynth.Feed
{
    public partial class MainPage : UserControl
    {
        string feedUrl;
        SynthMediaStreamSource source;
        Mixer mixer;
        DispatcherTimer timer;
        GenericTextSynth synth;
        bool playing;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.timer = new DispatcherTimer();
            this.timer.Interval = TimeSpan.FromMilliseconds(200);
            this.timer.Tick += new EventHandler(timer_Tick);
            this.timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (this.source != null && playing)
            {
                this.updateBox.Text = string.Format("Playing {0} of {1}.", this.synth.Index.ToString(), this.synth.Length.ToString());
                double percent = (double)this.synth.Index / (double)this.synth.Length * 1000;
                this.progress.Value = percent;
            }
        }

        void GetFeed()
        {
            playing = false;
            this.updateBox.Text = "Please wait...";
            this.playButton.IsEnabled = false;
            WebClient client = new WebClient();
            string thisUrl = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
            int index = thisUrl.LastIndexOf("/") + 1;
            string copyUrl = thisUrl.Substring(0, index) + "Copy.aspx?";
            copyUrl += "k=" + this.keywordsTextBox.Text;
            copyUrl += "&url=" + System.Windows.Browser.HttpUtility.UrlEncode(feedUrl);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(copyUrl, UriKind.Absolute));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            int index = e.Result.IndexOf("%DATA%");
            string indicesString = e.Result.Substring(0, index);
            string[] indexValues = indicesString.Split(',');
            List<int> indices = new List<int>();
            for (int i = 0; i < indexValues.Length; i++)
                indices.Add(int.Parse(indexValues[i]));

            this.updateBox.Text = "Yay.";
            this.playButton.IsEnabled = true;

            if (source == null)
            {
                source = new SynthMediaStreamSource(44100, 2);
                mixer = new Mixer();
                mixer.PassThrough = true;
                source.SampleMaker = mixer;
                this.media.SetSource(source);
                this.synth = new GenericTextSynth();
                mixer.Inputs.Add(synth);
            }

            synth.Load(e.Result.Substring(index+6), indices);
            this.media.Play();
            playing = true;
        }

       
        private void playButton_Click(object sender, RoutedEventArgs e)
        {
            playing = false;
            this.media.Stop();
            this.feedUrl = this.urlTextBox.Text;
            this.GetFeed();
        }

        private void sine_Checked(object sender, RoutedEventArgs e)
        {
            if (this.synth == null) return;

            IWaveForm waveForm = null;

            if (sine.IsChecked.Equals(true))
            {
                waveForm = new SineWaveForm();
            }
            else if (saw.IsChecked.Equals(true))
                waveForm = new SawWaveForm();
            else if (tri.IsChecked.Equals(true))
                waveForm = new TriangleWaveForm();
            else
                waveForm = new SquareWaveForm();

            foreach (Oscillator osc in this.synth.Voice.Oscillators)
            {
                osc.WaveForm = waveForm;
            }

        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (this.synth != null)
            {
                this.synth.Speed = (int)((Slider)sender).Value;
            }

        }

        private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (this.synth != null){
                this.synth.SlideScale = ((Slider)sender).Value;
            }
        }

    }
}
